package com.web.exiaodao.business.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.webstart.base.util.YamlUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.web.exiaodao.business.entity.Order;
import com.web.exiaodao.business.service.OrderService;

/**
 * @author eason.zt
 * @version V1.0
 * @Title: OrderController.java
 * @Package com.web.webstart.business.controller
 * @Description: 商品-订单表控制器
 * @date 2016-11-03 10:54:30
 */
@Controller
@RequestMapping("/cms/order")
public class OrderController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    /**
     * @param pageSize
     * @param status     //默认查询非删除3的数据,具体类型参照XaConstant.Status
     *                   @param sortData
     * @param jsonFilter
     * @return
     * @Title: findOrderNEStatusPage
     * @Description: 分页查询Order     * @param nextPage
     */
    @ResponseBody
    @RequestMapping(value = "findOrderNEStatusPage", method = RequestMethod.POST)
    public XaResult<Page<Order>> findOrderNEStatusPage(
            @RequestParam(defaultValue = "0") Integer nextPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "3") Integer status,
            @RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
            @RequestParam(defaultValue = "{}") String jsonFilter
    ) throws BusinessException {
        XaResult<Page<Order>> xr = new XaResult<Page<Order>>();
        try {
            Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
            Map<String, Object> filterParams = WebUitl.getParametersStartingWith(jsonFilter, "search_");
            xr =  orderService.findListNEStatusByFilter(status, filterParams, pageable);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }


    /**
     * @param modelId
     * @return
     * @Title: findOrderById
     * @Description: 根据ID查找单条实体
     */
    @ResponseBody
    @RequestMapping(value = "findOrderById", method = RequestMethod.POST)
    public XaResult<Order> findOrderById(
            @RequestParam Long modelId
    ) throws BusinessException {
        XaResult<Order> xr = new XaResult<Order>();
        try {
            xr = orderService.findOne(modelId);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }
    /**
     * @param modelId
     * @return
     * @Title: findOrderById
     * @Description: 根据ID查找单条实体
     */
    @ResponseBody
    @RequestMapping(value = "findOrderByIdDetail", method = RequestMethod.POST)
    public XaResult<List<Map<String, Object>>> findOrderByIdDetail(
            @RequestParam Long modelId
    ) throws BusinessException {
        XaResult<List<Map<String, Object>>> xr = new XaResult<List<Map<String, Object>>>();
        try {
            xr = orderService.findOneDetial(modelId);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @param model
     * @return
     * @Title: saveModel
     * @Description: 保存实体数据
     */
    @ResponseBody
    @RequestMapping(value = "saveOrder", method = RequestMethod.POST)
    public XaResult<Order> saveOrder(
            Order model
    ) throws BusinessException {
        XaResult<Order> xr = new XaResult<Order>();
        try {
            xr = orderService.saveOrUpdate(model);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }


    /**
     * @param ids
     * @return
     * @Title: sendOrders
     * @Description: 发货,保存快递单号
     */
    @ResponseBody
    @RequestMapping(value = "sendOrders", method = RequestMethod.POST)
    public XaResult<Boolean> saveOrder(
            @RequestParam	String ids, //这里是订单id,不是订单orderNO
            @RequestParam   String expressCompany,
            @RequestParam	String expressNumber
    ) throws BusinessException {
        XaResult<Boolean> xr = new XaResult<Boolean>();
        try {
            String[] arr=ids.split(",");
            xr =  orderService.sendOrders(arr, expressCompany, expressNumber);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @param modelIds 多个实体id,中间用逗号隔开
     * @param status   操作类型,status类型见XaConstant.Status,默认删除操作
     * @return
     * @Title: multiOperateOrderByIds
     * @Description: 批量操作多个实体状态, 根据status进行操作
     */
    @ResponseBody
    @RequestMapping(value = "operateOrderByIds", method = RequestMethod.POST)
    public XaResult<Order> operateOrderByIds(
            HttpServletRequest request,
            @RequestParam String modelIds,
            @RequestParam(defaultValue = "3") Integer status
    ) throws BusinessException {
        XaResult<Order> xr = new XaResult<Order>();
        try {
            xr =  orderService.multiOperate(modelIds, status);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    @ResponseBody
    @RequestMapping(value = "operateOrderStatusById", method = RequestMethod.POST)
    public XaResult<Order> operateOrderStatusById(
            HttpServletRequest request,
            @RequestParam Long orderId,
            @RequestParam String orderState
    ) throws BusinessException {
        XaResult<Order> xr = new XaResult<Order>();
        try {
            Order order = new Order();
            order.setId(orderId);
            order.setOrderState(orderState);
            xr =  orderService.saveOrUpdate(order);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    //快递公司
    @ResponseBody
    @RequestMapping(value = "expresscmps", method = RequestMethod.POST)
    public XaResult<List<String>> operateOrderStatusById(
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<List<String>> xr = new XaResult<>();
        try {
            List expressCompanys = (List) YamlUtils.yaml2Map("data.yml").get("expressCompanyArrays");
            xr.setObject(expressCompanys);
        } catch (Exception e) {
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            xr.error(XaConstant.Message.error);
        }
        return xr;
    }

    /**
     * @Title: upload
     * @Description: 导出文件到 office xls
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping(value = "fileDownload", method = RequestMethod.GET)
    public void fileDownload(
            @RequestParam(defaultValue = "{}") String jsonFilter,
            @RequestParam(required=false) String modelIds,
            HttpServletResponse response) throws BusinessException {
        try {
            jsonFilter = URLDecoder.decode(jsonFilter, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{'search_IN_id':'" +
                JSON.toJSONString(modelIds.split(JConstant.SYMBOL_DOT)) + "'}", "search_");
        orderService.exportdata(filterParams, response,modelIds);
    }
}

